﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4;
using IdentityServer4.Test;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using MvcAuthSample.Models;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace MvcAuthSample.Controllers
{
    public class AccountController : Controller
    {
        private readonly TestUserStore testUserStore;
        public AccountController(TestUserStore testUserStore)
        {
            this.testUserStore = testUserStore;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
       
        public IActionResult Login(string returnUrl)
        {

            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel loginViewModel, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                ViewData["ReturnUrl"] = returnUrl;
                var user = testUserStore.FindByUsername(loginViewModel.UserName);
                if (user == null)
                {
                    ModelState.AddModelError(nameof(loginViewModel.UserName), "username not exists");
                }
                else
                {
                    if (testUserStore.ValidateCredentials(loginViewModel.UserName, loginViewModel.Password))
                    {
                        var prpos = new AuthenticationProperties()
                        {
                            IsPersistent = true,
                            ExpiresUtc = DateTimeOffset.Now.Add(TimeSpan.FromHours(30))
                        };
                        await Microsoft.AspNetCore.Http.AuthenticationManagerExtensions.SignInAsync(HttpContext, user.SubjectId, user.Username, prpos);
                        return RedirectToLoacl(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError(nameof(loginViewModel.UserName), "login error");
                    }
                }
            }
            return View();
        }

        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync();
            return RedirectToAction("index", "home");
        }
        private IActionResult RedirectToLoacl(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return RedirectToAction(nameof(HomeController.Index), "home");
        }

        public IActionResult Register()
        {
            return View();
        }
     

    }
}
